package cn.yzgy.yzgyoa.common.utils;

import cn.yzgy.yzgyoa.common.crsp.StatusCode;
import cn.yzgy.yzgyoa.common.exception.SystemException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密工具类
 * 用于对密码等敏感信息进行加密
 *
 * @author Yqsen
 * @since 2019-8-22 11:11:02
 */
@Component
@SuppressWarnings("unused")
public class YzCrypto {

    private final HashedCredentialsMatcher hashedCredentialsMatcher;

    public YzCrypto(HashedCredentialsMatcher hashedCredentialsMatcher) {
        this.hashedCredentialsMatcher = hashedCredentialsMatcher;
    }

    /**
     * 获取经过Shiro编码后的密码
     *
     * @param password 密码
     * @param salt     salt
     * @return 加密后的算法
     */
    public String getEncodedPassword(String password, String salt) {
        // 密码生成
        password = getShaPassword(password);
        UsernamePasswordToken token = new UsernamePasswordToken("", password);
        ByteSource dealSalt = ByteSource.Util.bytes(salt);

        return new SimpleHash(hashedCredentialsMatcher.getHashAlgorithmName(),
                token.getCredentials(),
                dealSalt,
                hashedCredentialsMatcher.getHashIterations()).toString();
    }

    /**
     * 对密码进行sha操作
     *
     * @param password 密码
     * @return 经sha1后的密码
     */
    public String getShaPassword(String password){
        MessageDigest sha;
        String res;
        try {
            sha = MessageDigest.getInstance("SHA");
            sha.update(password.getBytes());
        } catch (NoSuchAlgorithmException | NullPointerException e) {
            throw new SystemException(StatusCode.EXCEPTION, e.getMessage());
        }
        return HexConvert.binary2HexString(sha.digest());
    }

}
